/**
 * *************************************
 * Copyright(c)2016 Dingdang Yixia
 * All Rights Reserved.
 *
 * @File: UserAccessServiceImpl.java
 * @Package: com.ddyx.service.impl
 * @Description:
 * @Version: V1.0
 * @Author: Yidong.Xiang
 * @Date: 2017年12月13日 下午5:35:53
 * <p>
 * *************************************
 */
package com.purchase.service.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.purchase.entity.*;
import com.purchase.mapper.*;
import com.purchase.service.CouponService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
//import com.purchase.entity.Employe;
//import com.purchase.mapper.EmployeMapper;
import com.purchase.service.IUserAccessService;
import com.purchase.util.DateUtil;
import com.purchase.util.JavaWebToken;
import com.purchase.util.LogInfo;
import com.purchase.util.MD5FileUtil;
import com.purchase.util.MyBeanUtils;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;
import com.purchase.util.WxUserAccessUtil;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @ClassName: UserAccessServiceImpl.java
 * @Module: 用户访问接口实现类
 * @Description: 实现微信账号访问接口
 *
 * @author: liuhoujie
 * @date: 2017年12月13日 下午5:35:53
 *
 */
@Slf4j
@Service
public class UserAccessServiceImpl implements IUserAccessService {
    @Resource
    WxUserMapper wxUserMapper;
    @Resource
    UserSessionMapper userSessionMapper;
    @Resource
    WxUserMemberMapper wxUserMemberMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private WithdrawMapper withdrawMapper;

    @Autowired
    private CouponService couponService;

    @Transactional
    @SuppressWarnings("unchecked")
    @Override
    public ResponseForm wechatUserlogin(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String code = paramMap.get("wxCode").toString();
            String storeNo = paramMap.get("storeNo").toString();
            //使用登录凭证 code获取openid和session_key
            JSONObject wxLoginInfo = WxUserAccessUtil.getSessionKeyOropenid(code, storeNo);
            String sessionKey = wxLoginInfo.getString("session_key");
            String openId = wxLoginInfo.getString("openid");
            //保存微信用户登录态，返回自有accessToken
            String sessionId = keepSession(openId, sessionKey);

            //wxCode只能用一次，用第二次的时候openId和sessionId为null值，提示
            if (null == openId || null == sessionId) {
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("PARAM_UNKNOWN");
                result.setTotal(0);
                return result;
            }
            //此逻辑应基于redis缓存实现
            //根据openid判断用户是否已存在，若不存在则创建用户，保存wxUid，wxSid，openId，sessionKey
            //若存在则返回wxUid。
            WxUser queryMap = new WxUser();
            queryMap.setOpenId(openId);
            WxUser user = wxUserMapper.selectOne(queryMap);
            String wxUid = "";
            if (user != null) {
                if (null != user.getWxUid())
                    wxUid = user.getWxUid();//该用户已存在
            }
            if (StringUtils.isBlank(wxUid)) {
                Date date = new Date();
                Timestamp timeStamp = new Timestamp(date.getTime());
                wxUid = UUID.randomUUID().toString();//分配用户ID
                WxUser newUser = new WxUser();
                newUser.setWxUid(wxUid);
                newUser.setOpenId(openId);
                newUser.setSessionKey(sessionKey);
                newUser.setCreateTime(timeStamp);
                wxUserMapper.insertSelective(newUser);//创建新用户
            }
            Map<String, String> userSessionInfo = new HashMap<String, String>();
            userSessionInfo.put("wxUid", wxUid);
            userSessionInfo.put("wxSid", sessionId);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setMessage("SID_VALID");
            result.setTotal(0);
            return result;
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage("用户登录错误");
            log.error(e + "用户登录错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return result;
    }


    @Transactional
    @SuppressWarnings("unchecked")
    @Override
    public ResponseForm authorize(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String verifyPhone = (String) paramMap.get("verifyPhone");
            String code = paramMap.get("wxCode").toString();
            String storeNo = paramMap.get("storeNo").toString();
            //使用登录凭证 code获取openid和session_key
            JSONObject wxLoginInfo = WxUserAccessUtil.getSessionKeyOropenid(code, storeNo);
            String sessionKey = wxLoginInfo.getString("session_key");
            String openId = wxLoginInfo.getString("openid");
            //保存微信用户登录态，返回自有accessToken
            String sessionId = keepSession(openId, sessionKey);

            //wxCode只能用一次，用第二次的时候openId和sessionId为null值，提示
            if (null == openId || null == sessionId) {
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("获取授权失败,请重式!");
                log.error("PARAM_UNKNOWN");
                result.setTotal(0);
                return result;
            }
            //此逻辑应基于redis缓存实现
            //根据openid判断用户是否已存在，若不存在则创建用户，保存wxUid，wxSid，openId，sessionKey
            //若存在则返回wxUid。
            WxUser user = new WxUser();
//			queryMap.setOpenId(openId);
//			WxUser user = wxUserMapper.selectOne(queryMap);
            user.setVerifyPhone(verifyPhone);
            user = wxUserMapper.selectOne(user);
            if (user == null) {
                result.setMessage("该手机用户不存在");
                result.setCode("400");
                result.setStatus(false);
                return result;
            }
            if (StringUtils.isBlank(user.getOpenId())) {
                WxUser bean = new WxUser();
                bean.setOpenId(openId);
                bean = wxUserMapper.selectOne(bean);
                if (bean != null) {
                    result.setMessage("该微信号已绑定其他手机号!");
                    result.setCode("400");
                    result.setStatus(false);
                    return result;
                }
            }
            if (StringUtils.isNotBlank(user.getOpenId()) && !openId.equals(user.getOpenId())) {
                result.setMessage("该手机号已绑定其他微信号!");
                result.setCode("400");
                result.setStatus(false);
                return result;
            }
            /*更新微信用户信息*/
            user.setOpenId(openId);
            user.setSessionKey(sessionKey);
            user.setCreateTime(new Date());
            wxUserMapper.updateByPrimaryKeySelective(user);
            /*返回wxUid和wxSid*/
            Map<String, String> userSessionInfo = new HashMap<String, String>();
            userSessionInfo.put("wxUid", user.getWxUid());
            userSessionInfo.put("wxSid", sessionId);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setMessage("SID_VALID");
            result.setTotal(0);
            return result;
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage("用户登录错误");
            log.error(e + "用户登录错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return result;
    }

    @Transactional
    @SuppressWarnings("unchecked")
    @Override
    public ResponseForm authorize2(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String code = paramMap.get("wxCode").toString();
            String storeNo = paramMap.get("storeNo").toString();
            //使用登录凭证 code获取openid和session_key
            JSONObject wxLoginInfo = WxUserAccessUtil.getSessionKeyOropenid(code, storeNo);
            String sessionKey = wxLoginInfo.getString("session_key");
            String openId = wxLoginInfo.getString("openid");
            //保存微信用户登录态，返回自有accessToken
            String sessionId = keepSession(openId, sessionKey);

            //推广码(推广人手机号)
            String inviteCode = (String) paramMap.get("inviteCode");

            //userId
            Integer userId = null;

            //verifyPhone 绑定手机号
            String verifyPhone = "";
            //wxCode只能用一次，用第二次的时候openId和sessionId为null值，提示
            if (null == openId || null == sessionId) {
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("wxCode已失效,请重新获取!");
                result.setTotal(0);
                return result;
            }
            //此逻辑应基于redis缓存实现
            //根据openid判断用户是否已存在，若不存在则创建用户，保存wxUid，wxSid，openId，sessionKey
            //若存在则返回wxUid。
            WxUser user = new WxUser();
            user.setOpenId(openId);
            user = wxUserMapper.selectOne(user);
//			if(user!=null )
//			{
//				if(null!=user.getWxUid())
//					wxUid=user.getWxUid();//该用户已存在
//			}
            String wxUid = "";
            if (user == null)//user为空说明为新用户,创建wxUid并保存推广码信息
            {
                Date date = new Date();
                Timestamp timeStamp = new Timestamp(date.getTime());
                wxUid = UUID.randomUUID().toString();//分配用户ID
                WxUser newUser = new WxUser();
                newUser.setWxUid(wxUid);
                newUser.setOpenId(openId);
                newUser.setSessionKey(sessionKey);
                newUser.setCreateTime(timeStamp);
                if (StringUtils.isNotBlank(inviteCode)) {
                    newUser.setInviteCode(inviteCode);
                }
                wxUserMapper.insertSelective(newUser);//创建新用户
                userId = newUser.getUserId();

                //新用户绑定新人优惠券
                couponService.bindNewUserCoupons(wxUid);
            } else {
                wxUid = user.getWxUid();
                userId = user.getUserId();
                verifyPhone = user.getVerifyPhone();
            }
            Map<String, String> userSessionInfo = new HashMap<>();
            userSessionInfo.put("wxUid", wxUid);
            userSessionInfo.put("wxSid", sessionId);
            userSessionInfo.put("verifyPhone", verifyPhone);

            //获取会员或代购角色
            WxUserMember wxUserMember = new WxUserMember();
            wxUserMember.setStatus(1);
            wxUserMember.setWxUid(wxUid);
            WxUserMember member = wxUserMemberMapper.selectOne(wxUserMember);
            if (member != null) {
                userSessionInfo.put("roleId", String.valueOf(member.getRoleId()));
            }

            Map<String, Object> loginInfo = new HashMap<>();
            loginInfo.put("userId", userId);
            userSessionInfo.put("sessionId", JavaWebToken.createJavaWebToken(loginInfo));

            result.setData(userSessionInfo);
            result.setCode("200");
            result.setStatus(true);
            result.setMessage("SID_VALID");
            result.setTotal(0);
            return result;
        } catch (Exception e) {
            result.setStatus(false);
            result.setCode("500");
            result.setMessage("用户登录错误");
            log.error(e + "用户登录错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 微信小程序用户登录态维护
     * @param openId        微信用户唯一标识
     * @param sessionKey    会话秘钥
     * @return sessionId    应用服务分配的sessionId
     */
    @Transactional
    public String keepSession(String openId, String sessionKey) {
        //计算sessionId
        StringBuffer sb = new StringBuffer();
        sb.append(openId).append(sessionKey);
        String sessionId = MD5FileUtil.getMD5String(sb.toString());

        //判断session是否过期，若过期则重新生成，否则返回原来的sessionId;
        //如果过期微信接口返回的sessionKey值不一样，自有生成的sessionId也不一样
        UserSession paramMap = new UserSession();
//		paramMap.setSessionId(sessionId);
//		int count = userSessionMapper.selectCount(paramMap);
//		if(count==0)
//		{
//			Date date = new Date();
//			UserSession session = new UserSession();
//			session.setSessionId(sessionId);
//			session.setOpenId(openId);
//			session.setSessionKey(sessionKey);
//			session.setCreateTime(date.getTime());
//			userSessionMapper.insert(session);
//		}
        paramMap.setOpenId(openId);
        paramMap = userSessionMapper.selectOne(paramMap);
        UserSession session = new UserSession();
        Date date = new Date();
        if (paramMap == null) {    /*如果没有session添加*/
            System.err.println("=======================SESSION=================INSERT=======================");
            session.setSessionId(sessionId);
            session.setOpenId(openId);
            session.setSessionKey(sessionKey);
            session.setCreateTime(date.getTime());
            userSessionMapper.insertSelective(session);
        } else {
            /*如果获取到session 更新session*/
            System.err.println("========================SESSION=================UPDATE========================");
            session.setId(paramMap.getId());
            session.setSessionId(sessionId);
            session.setOpenId(openId);
            session.setSessionKey(sessionKey);
            session.setCreateTime(date.getTime());
            userSessionMapper.updateByPrimaryKeySelective(session);
        }
        return sessionId;
    }

    @Transactional
    @SuppressWarnings("unchecked")
    public ResponseForm saveUserInfo(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        result.setStatus(false);
        result.setCode("400");
        result.setMessage("PARAM_UNKNOWN");
        result.setTotal(0);
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String wxUid = paramMap.get("wxUid").toString();
            String sessionId = paramMap.get("wxSid").toString();
            String encryptedData = paramMap.get("encryptedData").toString();
            if (StringUtils.isBlank(encryptedData)) {
                return result;
            }
            String signature = paramMap.get("signature").toString();
            String iv = paramMap.get("iv").toString();

            //---此逻辑修改为从redis中获取sessionKey
            UserSession queryMap = new UserSession();
            queryMap.setSessionId(sessionId);
            Map<String, String> map = new HashMap<String, String>();
            map.put("session_id", sessionId);
            UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
            if (null == session) {
                return result;
            }
            String sessionKey = session.getSessionKey();
            //解密用户信息
            JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
            if (null == userInfo) {
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("SESSION_EXPIRED");
                result.setTotal(0);
                return result;
            }
            String city = userInfo.getString("city");
            String country = userInfo.getString("country");
            String gender = userInfo.getString("gender");
            String headImage = userInfo.getString("avatarUrl");
            String language = userInfo.getString("language");
            String nickName = userInfo.getString("nickName");
            String province = userInfo.getString("province");
            String unionId = userInfo.getString("unionId");
            if (StringUtils.isBlank(nickName)) {
                {
                    result.setStatus(false);
                    result.setCode("400");
                    result.setMessage("SESSION_EXPIRED");
                    result.setTotal(0);
                    return result;
                }
            }
            nickName = new String(nickName.getBytes(), "UTF-8");
//			String mobile = userInfo.getString("");
            Date date = new Date();
            Timestamp timeStamp = new Timestamp(date.getTime());

            //更新微信用户信息:更新用户表
            WxUser user = new WxUser();
            user.setWxUid(wxUid);
            user.setCity(city);
            user.setCountry(country);
            user.setGender(gender);
            user.setHeadImage(headImage);
            user.setLanguage(language);
            user.setNickName(nickName);
            user.setProvince(province);
            user.setLatestOnlinetime(timeStamp);
            if (null != unionId)
                user.setUnionId(unionId);
            user.setSessionKey(sessionKey);
//			user.setMobile(mobile);
            System.err.println("=======================用户信息=============UPDATE================");
            Example example = new Example(WxUser.class);
            Criteria criteria = example.createCriteria();
            criteria.andEqualTo("wxUid", wxUid);
            int r = wxUserMapper.updateByExampleSelective(user, example);
            if (r == 0 && null != wxUid) {
                System.err.println("======================用户信息========INSERT==========================");
                wxUserMapper.insertSelective(user);
            }
            Map<String, String> userSessionInfo = new HashMap<String, String>();
            userSessionInfo.put("wxUid", wxUid);
            userSessionInfo.put("wxSid", sessionId);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setStatus(true);
            result.setMessage("SID_VALID");
            result.setTotal(1);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMessage("用户登录错误");
            log.error(e + "用户登录错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Transactional
    @SuppressWarnings("unchecked")
    public ResponseForm newSaveUserInfo(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        result.setStatus(false);
        result.setCode("400");
        result.setMessage("保存信息失败,请重试!");
        result.setTotal(0);
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String wxUid = paramMap.get("wxUid").toString();
            String sessionId = paramMap.get("wxSid").toString();
            String encryptedData = paramMap.get("encryptedData").toString();
            String verifyPhone = (String) paramMap.get("verifyPhone");
            if (StringUtils.isBlank(encryptedData)) {
                return result;
            }
            String signature = paramMap.get("signature").toString();
            String iv = paramMap.get("iv").toString();

            //---此逻辑修改为从redis中获取sessionKey
            UserSession queryMap = new UserSession();
            queryMap.setSessionId(sessionId);
            Map<String, String> map = new HashMap<String, String>();
            map.put("session_id", sessionId);
            UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
            if (null == session) {
                return result;
            }
            String sessionKey = session.getSessionKey();
            //解密用户信息
            JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
            if (null == userInfo) {
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("登录已过期,请重试!");
                log.error("SESSION_EXPIRED");
                result.setTotal(0);
                return result;
            }
            String city = userInfo.getString("city");
            String country = userInfo.getString("country");
            String gender = userInfo.getString("gender");
            String headImage = userInfo.getString("avatarUrl");
            String language = userInfo.getString("language");
            String nickName = userInfo.getString("nickName");
            String province = userInfo.getString("province");
            String unionId = userInfo.getString("unionId");
            if (StringUtils.isBlank(nickName)) {
                {
                    result.setStatus(false);
                    result.setCode("400");
                    result.setMessage("登录已过期,请重试!");
                    log.error("SESSION_EXPIRED");
                    result.setTotal(0);
                    return result;
                }
            }
            nickName = new String(nickName.getBytes(), "UTF-8");
//			String mobile = userInfo.getString("");
            Date date = new Date();
            Timestamp timeStamp = new Timestamp(date.getTime());

            //更新微信用户信息:更新用户表
            WxUser user = new WxUser();
            user.setWxUid(wxUid);
            user.setCity(city);
            user.setCountry(country);
            user.setGender(gender);
            user.setHeadImage(headImage);
            user.setLanguage(language);
            user.setNickName(nickName);
            user.setProvince(province);
            user.setLatestOnlinetime(timeStamp);
            if (null != unionId)
                user.setUnionId(unionId);
            user.setSessionKey(sessionKey);
//			user.setMobile(mobile);
            System.err.println("=======================用户信息=============UPDATE================");
            Example example = new Example(WxUser.class);
            Criteria criteria = example.createCriteria();
            criteria.andEqualTo("wxUid", wxUid);
            criteria.andEqualTo("verifyPhone", verifyPhone);
            int r = wxUserMapper.updateByExampleSelective(user, example);
            if (r == 0 && null != wxUid) {
                result.setCode("400");
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                return result;
            }
            Map<String, String> userSessionInfo = new HashMap<String, String>();
            userSessionInfo.put("wxUid", wxUid);
            userSessionInfo.put("wxSid", sessionId);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setStatus(true);
            result.setMessage("SID_VALID");
            result.setTotal(1);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMessage("登录错误");
            log.error(e + "登录错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Transactional
    @SuppressWarnings("unchecked")
    public ResponseForm saveUserInfo2(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        result.setStatus(false);
        result.setCode("400");
        result.setMessage("保存信息失败,请重试!");
        result.setTotal(0);
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String wxUid = paramMap.get("wxUid").toString();
            String sessionId = paramMap.get("wxSid").toString();
            String encryptedData = paramMap.get("encryptedData").toString();
//			String verifyPhone = (String) paramMap.get("verifyPhone");
            if (StringUtils.isBlank(encryptedData)) {
                return result;
            }
            String signature = paramMap.get("signature").toString();
            String iv = paramMap.get("iv").toString();

            //---此逻辑修改为从redis中获取sessionKey
            UserSession queryMap = new UserSession();
            queryMap.setSessionId(sessionId);
            Map<String, String> map = new HashMap<String, String>();
            map.put("session_id", sessionId);
            UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
            if (null == session) {
                return result;
            }
            String sessionKey = session.getSessionKey();
            //解密用户信息
            JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
            if (null == userInfo) {
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("登录已过期,请重试!");
                log.error("SESSION_EXPIRED");
                result.setTotal(0);
                return result;
            }
            String city = userInfo.getString("city");
            String country = userInfo.getString("country");
            String gender = userInfo.getString("gender");
            String headImage = userInfo.getString("avatarUrl");
            String language = userInfo.getString("language");
            String nickName = userInfo.getString("nickName");
            String province = userInfo.getString("province");
            String unionId = userInfo.getString("unionId");
            if (StringUtils.isBlank(nickName)) {
                {
                    result.setStatus(false);
                    result.setCode("400");
                    result.setMessage("登录已过期,请重试!");
                    log.error("SESSION_EXPIRED");
                    result.setTotal(0);
                    return result;
                }
            }
            nickName = new String(nickName.getBytes(), "UTF-8");
//			String mobile = userInfo.getString("");
            Date date = new Date();
            Timestamp timeStamp = new Timestamp(date.getTime());

            //更新微信用户信息:更新用户表
            WxUser user = new WxUser();
            user.setWxUid(wxUid);
            user.setCity(city);
            user.setCountry(country);
            user.setGender(gender);
            user.setHeadImage(headImage);
            user.setLanguage(language);
            user.setNickName(nickName);
            user.setProvince(province);
            user.setLatestOnlinetime(timeStamp);
            if (null != unionId)
                user.setUnionId(unionId);
            user.setSessionKey(sessionKey);
//			user.setMobile(mobile);
            System.err.println("=======================用户信息=============UPDATE================");
            Example example = new Example(WxUser.class);
            Criteria criteria = example.createCriteria();
            criteria.andEqualTo("wxUid", wxUid);
//			criteria.andEqualTo("verifyPhone", verifyPhone);
            int r = wxUserMapper.updateByExampleSelective(user, example);
            if (r == 0) {
                result.setCode("400");
                result.setStatus(false);
                result.setMessage("用户信息保存失败!");
                return result;
            }
            Map<String, String> userSessionInfo = new HashMap<>();
            userSessionInfo.put("wxUid", wxUid);
            userSessionInfo.put("wxSid", sessionId);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setStatus(true);
            result.setMessage("SID_VALID");
            result.setTotal(1);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode("500");
            result.setStatus(false);
            result.setMessage("登录错误");
            log.error(e + "登录错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseForm getUserRole(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String storeNo = paramMap.get("storeNo").toString();
            String wxUid = paramMap.get("wxUid").toString();
            String sessionId = paramMap.get("wxSid").toString();

            //从员表中查找
            int r = wxUserMapper.getUserRole(storeNo, wxUid);
            String roleId = r > 0 ? "1" : "0";
            Map<String, String> userSessionInfo = new HashMap<String, String>();
            userSessionInfo.put("wxUid", wxUid);
            userSessionInfo.put("wxSid", sessionId);
            userSessionInfo.put("storeNo", storeNo);
            userSessionInfo.put("roleId", roleId);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setMessage("ROLE_VALID");
            result.setTotal(1);
            return result;
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage("获取用户角色错误");
            log.error(e + "获取用户角色错误");
        }
        return result;
    }

    /**
     * 检查用户会话是否过期，如果过期重新分配一个新sessionId
     * @param requestForm
     * @return
     */
    @Override
    public ResponseForm checkSession(RequestForm requestForm) {
        return null;
    }

    @Override
    public ResponseForm getWxUid(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        @SuppressWarnings("unchecked")
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            String storeNo = paramMap.get("storeNo").toString();
            String mobile = paramMap.get("mobile").toString();

            // 从员表中查找
//			Employe queryMap = new Employe();
//			queryMap.setMobile(mobile);
//			queryMap.setStoreNo(storeNo);
//			Employe employe = employeMapper.selectOne(queryMap);

//			Map<String, String> userInfo = new HashMap<String, String>();
//			if (employe != null) {
//				String wxUid = employe.getWxUid();
//				if (null != wxUid && !"".equals(wxUid)) {
//					userInfo.put("storeNo", storeNo);
//					userInfo.put("wxUid", wxUid);
//					result.setData(userInfo);
//					result.setCode("200");
//					result.setMessage("WXUID_VALID");
//					result.setTotal(1);
//					return result;
//				}
//			}
            result.setCode("401");
            result.setMessage("WXUID_NOTEXIST");
            result.setTotal(0);
            return result;
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage("获取叮店用户Id错误");
            log.error(e + "获取叮店用户Id错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Transactional
    @Override
    public ResponseForm decodePhoneNumber(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        result.setStatus(false);
        result.setCode("0");
        result.setMessage("PARAM_UNKNOWN");
        result.setTotal(0);
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
//			String wxUid = paramMap.get("wxUid").toString();
            String sessionId = paramMap.get("wxSid").toString();
            String encryptedData = paramMap.get("encryptedData").toString();
//			String signature = paramMap.get("signature").toString();
            String iv = paramMap.get("iv").toString();

            //---此逻辑修改为从redis中获取sessionKey
//			UserSession queryMap = new UserSession();
//			queryMap.setSessionId(sessionId);
//			Map<String,String> map = new HashMap<String,String>();
//			map.put("session_id", sessionId);
            UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
            if (null == session) {
                return result;
            }
            String sessionKey = session.getSessionKey();//
            //解密用户信息
            JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
            if (null == userInfo) {
                return result;
            }
            String phoneNumber = userInfo.getString("phoneNumber");        //用户绑定的手机号（国外手机号会有区号）
            String purePhoneNumber = userInfo.getString("purePhoneNumber");//没有区号的手机号
            String countryCode = userInfo.getString("countryCode");        //	区号
//			Date date = new Date();
//			Timestamp timeStamp = new Timestamp(date.getTime());

            //更新微信用户信息:更新用户表
//			WxUser user = new WxUser();
//			user.setWxUid(wxUid);
//			user.setMobile(purePhoneNumber);
//			user.setCreateTime(timeStamp);
//			user.setMobile(mobile);
//			int r = userMapper.updateByPrimaryKeySelective(user);
//			if(r==0 && null!=wxUid)
//				userMapper.insert(user);
            Map<String, String> userSessionInfo = new HashMap<String, String>();
            userSessionInfo.put("phoneNumber", phoneNumber);
            userSessionInfo.put("purePhoneNumber", purePhoneNumber);
            userSessionInfo.put("countryCode", countryCode);
            result.setStatus(true);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setMessage("SID_VALID");
            result.setTotal(1);
            return result;
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage("手机号参数转换错误");
            log.error(e + "手机号参数转换错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Transactional
    @Override
    public ResponseForm pullPhone(RequestForm requestForm) {
        ResponseForm result = new ResponseForm();
        result.setStatus(false);
        result.setCode("0");
        result.setMessage("PARAM_UNKNOWN");
        result.setTotal(0);
        Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
        try {
            Map<String, String> userSessionInfo = new HashMap<String, String>();
            String wxUid = paramMap.get("wxUid").toString();
            String sessionId = paramMap.get("wxSid").toString();
            String encryptedData = paramMap.get("encryptedData").toString();
//			String signature = paramMap.get("signature").toString();
            String iv = paramMap.get("iv").toString();

            //先获从数据库获取用户绑定手机
            WxUser user = new WxUser();
            user.setWxUid(wxUid);
            user = wxUserMapper.selectOne(user);
            if (user != null && StringUtils.isNotBlank(user.getVerifyPhone())) {
                userSessionInfo.put("purePhoneNumber", user.getVerifyPhone());
                result.setData(userSessionInfo);
                result.setStatus(true);
                result.setCode("200");
                result.setMessage("该用户已绑定手机号!");
                return result;
            }
            //---此逻辑修改为从redis中获取sessionKey
//			UserSession queryMap = new UserSession();
//			queryMap.setSessionId(sessionId);
//			Map<String,String> map = new HashMap<String,String>();
//			map.put("session_id", sessionId);
            UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
            if (null == session) {
                return result;
            }
            String sessionKey = session.getSessionKey();//
            //解密用户信息
            JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
            if (null == userInfo) {
                return result;
            }
            String phoneNumber = userInfo.getString("phoneNumber");        //用户绑定的手机号（国外手机号会有区号）
            String purePhoneNumber = userInfo.getString("purePhoneNumber");//没有区号的手机号
            String countryCode = userInfo.getString("countryCode");        //	区号
            if (StringUtils.isBlank(purePhoneNumber)) {
                result.setCode("400");
                result.setMessage("获取手机号失败,session失效或该微信用户无手机号!");
                result.setStatus(false);
                return result;
            }
            Date date = new Date();
            Timestamp timeStamp = new Timestamp(date.getTime());
            //更新微信用户信息:更新用户表
            Integer userId = user.getUserId();
            user = new WxUser();
            user.setUserId(userId);
            user.setWxUid(wxUid);
            user.setVerifyPhone(purePhoneNumber);
            user.setCreateTime(timeStamp);
            int r = wxUserMapper.updateByPrimaryKeySelective(user);
//			if(r==0 && null!=wxUid)
//				userMapper.insert(user);
//			userSessionInfo.put("phoneNumber", phoneNumber);
            userSessionInfo.put("purePhoneNumber", purePhoneNumber);
//			userSessionInfo.put("countryCode", countryCode);
            result.setStatus(true);
            result.setData(userSessionInfo);
            result.setCode("200");
            result.setMessage("拉取手机号授权成功!");
//			result.setTotal(1);
            return result;
        } catch (Exception e) {
            result.setCode("500");
            result.setStatus(false);
            result.setMessage("手机号参数转换错误");
            log.error(e + "手机号参数转换错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /*-------------------------后台用户相关管理-----------------------------------*/

    @Override
    public ResponseForm wxUserList(RequestForm param) {
        ResponseForm result = new ResponseForm();
        try {
            Map<String, Object> paramMap = (Map<String, Object>) param.getData();
            com.purchase.util.Page.parsePage(paramMap);
            Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
            List<Map<String, Object>> list = wxUserMapper.getWxUserList(paramMap);
            result.setData(list);
            result.setTotal((int) pageHelper.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error(LogInfo.ERROR);
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseForm setMember(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            String wxUid = (String) paramMap.get("wxUid");
            String roleId = (String) paramMap.get("roleId");
            if (!StringUtils.isNotBlank(wxUid)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }
            if (roleId.equals("1")) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }

            WxUserMember wxUserMember = new WxUserMember();
            MyBeanUtils.populate(wxUserMember, paramMap);
            wxUserMember.setCreateTime(new Date());
            wxUserMember.setStartTime(new Date());
            wxUserMember.setStatus(1);

            Date endTime = null;
            if (wxUserMember.getRoleId() == 2) {
                //2=会员
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar specialDate = Calendar.getInstance();
                specialDate.add(Calendar.YEAR, 1); //特定时间的1年后
                endTime = specialDate.getTime();

                //查询有效会员优惠券
                List<Coupon> memberCoupons = couponMapper.getMemberCoupons();
                //给支付成功的会员绑定优惠券
                List<Map<String, Object>> receivableIdList = new ArrayList<>();
                for (Coupon memberCoupon : memberCoupons) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("wxUid", wxUid);
                    map.put("couponId", memberCoupon.getId());
                    receivableIdList.add(map);
                }
                couponMapper.createCouponUser(receivableIdList);
            }
            if (wxUserMember.getRoleId() == 3) {
                //3=代购
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar specialDate = Calendar.getInstance();
                specialDate.add(Calendar.YEAR, 100); //特定时间的100年后
                endTime = specialDate.getTime();

                //初始化代购提现数据
                Withdraw withdraw = new Withdraw();
                withdraw.setWxUid(wxUid);
                withdrawMapper.insert(withdraw);
            }
            wxUserMember.setEndTime(endTime);
            wxUserMemberMapper.insertSelective(wxUserMember);

            log.debug("恭喜" + wxUid + "喜提会员");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error(LogInfo.ERROR);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseForm setMemberEdit(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            String memberId = (String) paramMap.get("memberId");
            String roleId = (String) paramMap.get("roleId");
            String wxUid = (String) paramMap.get("wxUid");
            if (!StringUtils.isNotBlank(memberId)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }
            if (!roleId.equals("2")) {
                result.setStatus(false);
                result.setMessage("只有会员才能升级代购");
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }
            WxUserMember wxUserMember = new WxUserMember();
            MyBeanUtils.populate(wxUserMember, paramMap);
            wxUserMember.setId(Integer.parseInt(memberId));
            wxUserMember.setCreateTime(new Date());
            wxUserMember.setStatus(1);
            wxUserMember.setRoleId(3);
            wxUserMember.setInviteWxUid(null);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar specialDate = Calendar.getInstance();
            specialDate.add(Calendar.YEAR, 100); //特定时间的100年后
            Date endTime = specialDate.getTime();

            wxUserMember.setEndTime(endTime);
            wxUserMemberMapper.updateByPrimaryKeySelective(wxUserMember);

            //取消代购绑定关系
            HashMap<String, Object> undoMap = new HashMap<>();
            undoMap.put("wxUid", wxUid);
            wxUserMemberMapper.undoInviteWxUid(undoMap);

            //初始化代购提现数据
            Withdraw withdraw = new Withdraw();
            withdraw.setWxUid(wxUid);
            withdrawMapper.insert(withdraw);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error(LogInfo.ERROR);
        }
        return result;
    }

}
